package com.monkey.util.sms;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.monkey.util.DateUtil;
import com.monkey.util.WebConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.*;

/**
 * desc:
 * auth: chenxiaobin
 * data: 2018/1/26.
 */
@Component
public class SMSTXUtil {
    private static Logger logger = LoggerFactory.getLogger(SMSTXUtil.class);
    private RestTemplate restTemplate = new RestTemplate();

    @Resource
    private WebConfig webConfig = null;

    @Resource
    private DateUtil dateUtil = null;

    // 腾讯
    public boolean send(String phone, int code, int timeout) {
        logger.info("send sms:{}, {}", phone, code);

        Date now = new Date();
        long time = now.getTime() / 1000;
        int rand = (int) (Math.random() * 100000);
        String url = webConfig.get("system.sms.url");
        String appid = webConfig.get("system.sms.appid");
        String apikey = webConfig.get("system.sms.apikey");
        int template = webConfig.getInt("system.sms.template");

        url = String.format(url, appid, rand);
        String sig = String.format("appkey=%s&random=%d&time=%s&mobile=%s", apikey, rand, time, phone);

        // sha-256
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(sig.getBytes());
            byte[] byteBuffer = md.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (1 == hex.length()) {
                    sb.append('0');
                }
                sb.append(hex);
            }
            sig = sb.toString();
        } catch (Exception e) {
            logger.info("send sms sha error:{}, {}", phone, code);
            return false;
        }

        List<String> p1 = new ArrayList<>();
        p1.add(String.valueOf(code));
        p1.add(String.valueOf(timeout));

        Map<String, Object> p2 = new HashMap<>();
        p2.put("mobile", phone);
        p2.put("nationcode", "86");

        Map<String, Object> params = new HashMap<>();
        params.put("ext", "");
        params.put("extend", "");
        params.put("params", p1);
        params.put("sig", sig);
        params.put("sign", "");
        params.put("tel", p2);
        params.put("time", time);
        params.put("tpl_id", template);

        // 远程调用
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);

        try {
            ResponseEntity<String> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            if (respEntity.getStatusCode().toString().equals("200")) {
                logger.info("send sms success:{}, {}", phone, code);
                return true;
            }
        } catch (Exception e) {
            logger.info("send sms error:{}, {}, {}", phone, code, e);
        }
        return false;
    }
}
